//
//  StockTableQuoteSetup.m
//  iStock Global
//
//  Created by Andy on 2010/11/24.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "StockTableQuoteSetup.h"
#import "StockTableQuoteCell.h"
#import "AppDelegate.h"
#import "HTMLNode.h"
#import "HTMLParser.h"
#import "EPUploader.h"

#include <unistd.h>

 

@implementation StockTableQuoteSetup

@synthesize AppleDeglate;
@synthesize delegate_UIPopoverController;
@synthesize delegate;

#pragma mark -
#pragma mark Initialization

-(void)loadView {
	
	upload_Tabel_Caption_FTP=@"FTP Wait...";
	upload_Tabel_Caption_HTTP=@"HTTP Wait...";    
	UIView *mainview;
    UINavigationBar *nav;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
        
        if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
            //垂直
            
            mainview=[[[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 600.0f, 600.0f)] autorelease];
          
            self.view=mainview;
            self.view.backgroundColor=[UIColor lightTextColor];
            
            nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 540.0f, 48.0f)];
            myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f, 540.0f, 580.0f)  style:UITableViewStyleGrouped];  
            
            pick=[[UIPickerView alloc ]initWithFrame:CGRectMake(100.0f, 246.0f, 320.0f, 216.0f)];                         
        }
        else{
            mainview=[[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
            nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];
            
            self.view=mainview;
            self.view.backgroundColor=[UIColor lightTextColor];
            
            myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f, 320.0f, 212.0f)  style:UITableViewStyleGrouped]; 
            
            pick=[[UIPickerView alloc ]initWithFrame:CGRectMake(0.0f, 246.0f, 320.0f, 216.0f)];         
        
        }         
        
        
        
        
    }
    else{
        mainview=[[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
        nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];
        self.view=mainview;
        self.view.backgroundColor=[UIColor lightTextColor];
        
        myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f, 320.0f,  self.view.frame.size.height)  style:UITableViewStyleGrouped]; 
        
        pick=[[UIPickerView alloc ]initWithFrame:CGRectMake(0.0f, self.view.frame.size.height-216, 320.0f, 216.0f)];
    }    
       
    
	
	
		
		
	
	UIBarButtonItem *barButton ;
	barButton = [[UIBarButtonItem alloc] initWithTitle:  NSLocalizedString(@"Done",@"完成")  style:UIBarButtonItemStylePlain target:self action:@selector(slideOut)];
	UINavigationItem *item;
	item = [[UINavigationItem alloc] initWithTitle:NSLocalizedString(@"Column Form" , @"欄位格式" ) ];
	[item setRightBarButtonItem: barButton];
	[nav pushNavigationItem:item animated:NO];	
	[item release];
 
	
	 	
	
	
    myTable.dataSource = self;	//連結資料 UITableViewDataSource
	myTable.delegate=self; //連結動作 UITableViewDelegate	
	[self.view addSubview:myTable];
	
	
	
	
	
	//[self.view addSubview:headerbutton];
	[mainview addSubview:nav ];	
	[nav release];
	
	pick.delegate=self;
	pick.showsSelectionIndicator=YES;
	[pick reloadAllComponents];	
	 
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	 //選擇訂位	
	[pick selectRow:[[prefs objectForKey:@"tableR0" ] intValue ] inComponent:0 animated:YES];
	[pick selectRow:[[prefs objectForKey:@"tableR1" ] intValue ] inComponent:1 animated:YES];
	[pick selectRow:[[prefs objectForKey:@"tableR2" ] intValue ] inComponent:2 animated:YES];	
	 
	[self.view addSubview:pick];	
	
	
	
	
}
-(id)initWithpicka1:(NSMutableArray *)apicka1 picka2:(NSMutableArray *)apicka2 picka3:(NSMutableArray *)apicka3 objecta:(NSMutableArray *)oba{
    self= [super initWithNibName:nil bundle:nil];
    if (self) {
	   picka1=apicka1;
	   picka2=apicka2;
	   picka3=apicka3;
	   download_data_obj=oba;	   
   }
	return self;
}
#pragma mark -
#pragma mark  退出至上一層
-(void)slideOut{
	
     
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        //[delegate_UIPopoverController dismissPopoverAnimated:YES]; 
        
        if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ){
            //垂直
            [self dismissModalViewControllerAnimated:YES];  
            
            [[(AppDelegate * )AppleDeglate Master_popController] presentPopoverFromBarButtonItem: 
             [(SplitViewDelegate *)[(AppDelegate * )AppleDeglate splitViewDelegate] showmasterUIBarButtonItem]  permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];              
            
            
        }
        else{
            //水平
            [delegate_UIPopoverController dismissPopoverAnimated:YES]; 
            
            
        }
        
        
        
        
        
        
        
    }    
	else{
        
    }    
    [self.delegate aflipsideViewControllerDidFinish:self identify:@"slideOut"];	       
    
    
    
    
    
}

#pragma mark -
#pragma mark  表格事件

//區塊數量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	//取出設定檔資料 是否進行最佳化
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	 
	if ([[prefs objectForKey:@"isManager"] boolValue]==YES) {
		return 5;		 			  
	}
	else {
		return 1;
	}

	
	
	
	
}
//區塊與列數量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return 1;
}
//表格內容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
	switch (indexPath.section) {
		case 0:
		{
			static NSString *CellIdentifier = @"StockTableQuoteCell";
			StockTableQuoteCell *cell ;
			cell = [[[StockTableQuoteCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
			//第1列欄位
		    {
				//解析 有幾行				
				NSArray *csvLinesR0 = [[picka1 objectAtIndex:[[prefs objectForKey: @"tableR0" ] intValue] ]  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
				if ([csvLinesR0 count]==1) {
					cell.c0r0.frame=CGRectMake(10, 10, 100, 40);
					cell.c0r1.highlighted=YES;
					cell.c0r2.hidden=YES;
					
					cell.c0r0.text=[csvLinesR0 objectAtIndex:0];
					cell.c0r0.font=[UIFont boldSystemFontOfSize:15];
					 				
					
					cell.c0r0.backgroundColor=[UIColor clearColor];
					
					cell.c0r0.textColor=[UIColor whiteColor];
				}
				else if ([csvLinesR0 count]==2) {
					cell.c0r0.frame=CGRectMake(10, 10, 100, 20);	
					cell.c0r1.frame=CGRectMake(10, 32, 100, 20);
					cell.c0r2.hidden=YES;
					
					cell.c0r0.text=[csvLinesR0 objectAtIndex:0];
					cell.c0r1.text=[csvLinesR0 objectAtIndex:1];
					cell.c0r0.font=[UIFont boldSystemFontOfSize:15];
					cell.c0r1.font=[UIFont boldSystemFontOfSize:15];					
					
					cell.c0r0.backgroundColor=[UIColor clearColor];
					cell.c0r1.backgroundColor=[UIColor clearColor];
					
					cell.c0r0.textColor=[UIColor whiteColor];
					cell.c0r1.textColor=[UIColor yellowColor];				
				}
				else if ([csvLinesR0 count]==3) {
					cell.c0r0.frame=CGRectMake(10, 0, 100,  20);	
					cell.c0r1.frame=CGRectMake(10, 20, 100, 20);
					cell.c0r2.frame=CGRectMake(10, 40, 100, 20);
					
					cell.c0r0.text=[csvLinesR0 objectAtIndex:0];
					cell.c0r1.text=[csvLinesR0 objectAtIndex:1];
					cell.c0r2.text=[csvLinesR0 objectAtIndex:2];
					cell.c0r0.font=[UIFont boldSystemFontOfSize:13];
					cell.c0r1.font=[UIFont boldSystemFontOfSize:13];
					cell.c0r2.font=[UIFont boldSystemFontOfSize:13];					
					
					
					cell.c0r0.backgroundColor=[UIColor clearColor];
					cell.c0r1.backgroundColor=[UIColor clearColor];
					cell.c0r2.backgroundColor=[UIColor clearColor];
					
					cell.c0r0.textColor=[UIColor whiteColor];
					cell.c0r1.textColor=[UIColor yellowColor];				
					cell.c0r2.textColor=[UIColor whiteColor];				
					
				}			
				
			}
			//第2列欄位
		    {
				//解析 有幾行				
				NSArray *csvLinesR1 = [[picka2 objectAtIndex:[[prefs objectForKey: @"tableR1" ] intValue] ]  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
				if ([csvLinesR1 count]==1) {
					cell.c1r0.frame=CGRectMake(110, 10, 100, 40);
					cell.c1r1.highlighted=YES;
					cell.c1r2.hidden=YES;
					
					cell.c1r0.text=[csvLinesR1 objectAtIndex:0];
					cell.c1r0.font=[UIFont boldSystemFontOfSize:15];
					cell.c1r0.backgroundColor=[UIColor clearColor];
					
					cell.c1r0.textColor=[UIColor whiteColor];
				}
				else if ([csvLinesR1 count]==2) {
					cell.c1r0.frame=CGRectMake(110, 10, 100, 20);	
					cell.c1r1.frame=CGRectMake(110, 32, 100, 20);
					cell.c1r2.hidden=YES;
					
					cell.c1r0.text=[csvLinesR1 objectAtIndex:0];
					cell.c1r1.text=[csvLinesR1 objectAtIndex:1];
					cell.c1r0.font=[UIFont boldSystemFontOfSize:15];
					cell.c1r1.font=[UIFont boldSystemFontOfSize:15];					
					
					
					cell.c1r0.backgroundColor=[UIColor clearColor];
					cell.c1r1.backgroundColor=[UIColor clearColor];
					
					cell.c1r0.textColor=[UIColor whiteColor];
					cell.c1r1.textColor=[UIColor yellowColor];				
				}
				else if ([csvLinesR1 count]==3) {
					cell.c1r0.frame=CGRectMake(110, 0, 100,  20);	
					cell.c1r1.frame=CGRectMake(110, 20, 100, 20);
					cell.c1r2.frame=CGRectMake(110, 40, 100, 20);
					
					cell.c1r0.text=[csvLinesR1 objectAtIndex:0];
					cell.c1r1.text=[csvLinesR1 objectAtIndex:1];
					cell.c1r2.text=[csvLinesR1 objectAtIndex:2];
					cell.c1r0.font=[UIFont boldSystemFontOfSize:13];
					cell.c1r1.font=[UIFont boldSystemFontOfSize:13];
					cell.c1r2.font=[UIFont boldSystemFontOfSize:13];
					
					cell.c1r0.backgroundColor=[UIColor clearColor];
					cell.c1r1.backgroundColor=[UIColor clearColor];
					cell.c1r2.backgroundColor=[UIColor clearColor];
					
					cell.c1r0.textColor=[UIColor whiteColor];
					cell.c1r1.textColor=[UIColor yellowColor];				
					cell.c1r2.textColor=[UIColor whiteColor];				
					
				}			
				
			}			
			//第3列欄位
		    {
				//解析 有幾行				
				NSArray *csvLinesR2 = [[picka3 objectAtIndex:[[prefs objectForKey: @"tableR2" ] intValue] ]  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
				if ([csvLinesR2 count]==1) {
					cell.c2r0.frame=CGRectMake(210, 10, 100, 40);
					cell.c2r1.highlighted=YES;
					cell.c2r2.hidden=YES;
					
					cell.c2r0.text=[csvLinesR2 objectAtIndex:0];
					cell.c2r0.font=[UIFont boldSystemFontOfSize:15];					
					
					cell.c2r0.backgroundColor=[UIColor clearColor];
					
					cell.c2r0.textColor=[UIColor whiteColor];
				}
				else if ([csvLinesR2 count]==2) {
					cell.c2r0.frame=CGRectMake(210, 10, 100, 20);	
					cell.c2r1.frame=CGRectMake(210, 32, 100, 20);
					cell.c2r2.hidden=YES;
					
					cell.c2r0.text=[csvLinesR2 objectAtIndex:0];
					cell.c2r1.text=[csvLinesR2 objectAtIndex:1];
					
					cell.c2r0.font=[UIFont boldSystemFontOfSize:15];
					cell.c2r1.font=[UIFont boldSystemFontOfSize:15];
				 			
					
					cell.c2r0.backgroundColor=[UIColor clearColor];
					cell.c2r1.backgroundColor=[UIColor clearColor];
					
					cell.c2r0.textColor=[UIColor whiteColor];
					cell.c2r1.textColor=[UIColor yellowColor];				
				}
				else if ([csvLinesR2 count]==3) {
					cell.c2r0.frame=CGRectMake(210, 0, 100,  20);	
					cell.c2r1.frame=CGRectMake(210, 20, 100, 20);
					cell.c2r2.frame=CGRectMake(210, 40, 100, 20);
					
					cell.c2r0.text=[csvLinesR2 objectAtIndex:0];
					cell.c2r1.text=[csvLinesR2 objectAtIndex:1];
					cell.c2r2.text=[csvLinesR2 objectAtIndex:2];
					
					cell.c2r0.font=[UIFont boldSystemFontOfSize:13];
					cell.c2r1.font=[UIFont boldSystemFontOfSize:13];
					cell.c2r2.font=[UIFont boldSystemFontOfSize:13];
					
					cell.c2r0.backgroundColor=[UIColor clearColor];
					cell.c2r1.backgroundColor=[UIColor clearColor];
					cell.c2r2.backgroundColor=[UIColor clearColor];
					
					cell.c2r0.textColor=[UIColor whiteColor];
					cell.c2r1.textColor=[UIColor yellowColor];				
					cell.c2r2.textColor=[UIColor whiteColor];				
					
				}			
				
			}			
			return cell;			
			break;
		}
		case 1:
		{	
			static NSString *CellIdentifier = @"Cell";
			UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			}
			cell.textLabel.text=@"計算最佳化";
			return cell;			
			break;
			
		}			
		case 2:
		{	
			static NSString *CellIdentifier = @"Cell";
			UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			}
			cell.textLabel.text=@"每日資料處理:FTP";
			return cell;			
			break;
			
		}	
        case 3:
		{	
			static NSString *CellIdentifier = @"Cell";
			UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			}
			cell.textLabel.text=@"每日資料處理:HTTP";
			return cell;			
			break;
			
		}	   
            
		case 4:
		{	
			static NSString *CellIdentifier = @"Cell";
			UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			}
			cell.textLabel.text=@"至Yahoo取出代碼";
			return cell;			
			break;
			
		}			
            
		default:
			break;
	}
	
	
	
	return nil;
		
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	
	switch (indexPath.section) {
		
		case 1:{
			//計算最佳化
			[self.delegate aflipsideViewControllerDidFinish:self identify:@"slideOut_opt"];
			 
			break;
		}
		
		case 2:{
			//FTP
            [self upload_action:@"FTP"];
			break;
			
		}
        case 3:{
			//HTTP
            [self upload_action:@"HTTP"];
			break;
			
		}    
            
		case 4:{
			//至yahoo取出代嗎
             [self getAlbumInfo];
           // [self getAlbumInfo_example];
			break;
			
		}
	
			
		default:
			break;
	}
	
	
}
NSInteger comparator_Symbola_UP( DataObject *d1, DataObject *d2, void *context ){
	return [ d1.symbol compare: d2.symbol];
} 

//設定表格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
	return 60;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	
	NSString *title = nil;
	switch (section) {
		case 0:
			title = NSLocalizedString(@"Column Style Example", @"欄位範例" );
			break;
	 
		default:
			break;
	}
	return title;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
	NSString *title = nil;
	switch (section) {
		case 0:{
			//版本字串
		    title =NSLocalizedString(@"Divid row into tree column form.Please use the selector to choice which form style you want to show.", @"每列拆分成三個欄位,請以下面選擇器,分別選擇所要顯示的資料種類");
			break;
		}
        case 2:{
			//FTP
		    title =upload_Tabel_Caption_FTP;
			break;
		}    
        case 3:{
			//HTP
		    title =upload_Tabel_Caption_HTTP;
			break;
		} 
            
			
		default:
			break;
	}
	return title;	
	
	
}
#pragma mark -
#pragma mark  至yahoo取出代嗎
//解析下載的資料
-(BOOL)showSongList:(NSString*)string
{
    
    BOOL loop;
    loop=NO;
    
    //取出前後段文
	NSString *matchPattern = @"Exchange.+</tbody></table>";    
    NSRange range = [string rangeOfString:matchPattern 
                                  options:NSRegularExpressionSearch];
	//NSMutableString *outputString = [[NSMutableString alloc] init];
    
    //表示可以截取到文章
    if(range.location != NSNotFound)
	{
		
        NSError *error = nil;
        
        NSString *html;
        NSString *matchString = [string substringWithRange:range];        
        html=matchString;
        
        HTMLParser *rawparser = [[HTMLParser alloc] initWithString:html error:&error];
        HTMLNode *rawbodyNode = [rawparser body];
        
        //找出列  節點的開頭是tr
        NSArray *RawNodes = [rawbodyNode findChildTags:@"tr"];
        int raw=1;
        for (HTMLNode *rawNode in RawNodes) {
            //找到 class="yui-dt-even" or class="yui-dt-even"
            
            if ([[rawNode getAttributeNamed:@"class"] isEqualToString:@"yui-dt-odd"] || [[rawNode getAttributeNamed:@"class"] isEqualToString:@"yui-dt-even"] ) {
                
                // NSLog(@"列%i 找到列的原始資料=%@",raw, [rawNode rawContents]); 
                
                //針對每個列 拆出行 column
                
                HTMLParser *columnparser = [[HTMLParser alloc] initWithString:[rawNode rawContents] error:&error];
                HTMLNode *columnbodyNode = [columnparser body];
                //找出行  節點的開頭是td           
                NSArray *ColumnNodes = [columnbodyNode findChildTags:@"td"]; 
                
                int column=1;
                
                NSString *codes=@"";
                NSString *names=@"";
                NSString *types=@"";
                NSString *industrys=@"";
                NSString *exchanges=@"";
                
                for (HTMLNode *columnNode in ColumnNodes) {
                    
                    
                    
                    if (column==1) { 
                        //symbol
                        
                        //第一行是 代號名稱 並且裡面含有url 所以要再度解析
                        
                        HTMLParser *codeparser = [[HTMLParser alloc] initWithString:[columnNode rawContents] error:&error];
                        HTMLNode *codebodyNode = [codeparser body];
                        //股票代碼藏在更深入一層的 <a>
                        NSArray *codeNodes = [codebodyNode findChildTags:@"a"]; 
                        
                        for (HTMLNode *codeNode in codeNodes) {
                            
                            // NSLog(@"code=%@",[codeNode contents]); //contents 表示不含有html標籤<>  ,rawContents 含有標簽                        
                            codes=[codeNode contents];                        
                        }
                        [codeparser release];
                    }
                    else if(column==2){
                        //name
                        
                        if ([columnNode contents] == nil) {
                            names=codes;
                        }
                        else{
                            names=[columnNode contents]; 
                        }
                        
                        
                    }              
                    else if(column==3){
                        //Last price
                        
                        
                        
                    }         
                    else if(column==4){
                        //Type
                        
                        if ([columnNode contents] == nil) {
                            types=@"N/A";
                        }
                        else{
                            types=[columnNode contents]; 
                        }
                        
                        
                    }                     
                    else if(column==5){
                        //Industry
                        
                        if ([columnNode contents] == nil) {
                            industrys=@"Undifine";
                        }
                        else{
                            industrys=[columnNode contents]; 
                        }
                        
                        
                    }                     
                    else if(column==6){
                        //Exchange
                        
                        if ([columnNode contents] == nil) {
                            exchanges=@"N/A";
                        }
                        else{
                            exchanges=[columnNode contents]; 
                        }
                        
                        
                    }                     
                    
                    //  NSLog(@"行%i=%@",column,[columnNode contents]);                
                    
                    column=column+1;
                    
                    
                }
                // NSLog(@"列%i 代碼=%@ 名稱=%@ Type=%@ Industry=%@ Exchanges=%@",raw,codes,names,types,industrys,exchanges);             
                
                //取出的資料轉入到公用陣列
                if ( [code_array indexOfObject:codes] ==NSNotFound) {
                    [code_array addObject:codes];
                    [name_array addObject:names];
                    [type_array addObject:types];
                    [industry_array addObject:industrys];
                    [exchange_array addObject:exchanges];
                    
                    
                }
                
                
                
                [columnparser release];            
                raw=raw+1;
            }
            
            else{
                NSLog(@"不是列的原始資料=%@", [rawNode rawContents]);             
                
            }
            
        }
        
        [rawparser release];       
        
        
        
        
        
        
        NSLog(@"本次分析檔數=%i 累計分析檔數=%i",raw,[code_array count]);
        
        if (raw>1) {
            //分析檔數超過2 表示下次還要繼續分析
            loop=YES;
        }        
        
        
        
	}
    
    return loop;
    
}
-(void)getAlbumInfo_example
{
    
    //標記:html 解析   
    
    /*
     複製
     HTMLNode.h
     HTMLNode.m
     HTMLParser.h
     HTMLParser.m     
     
     1. Open Your project in XCode and drag and drop all .h & .m Files into an appropriate folder
     2. In the project settings add "/usr/include/libxml2" to the "header search paths" field
     3. Ctrl Click the Frameworks group choose Add -> Existing Frameworks and from the list choose libxml2.dylib    
  
     example:
     NSError *error = nil;
     NSString *html = 
     @"<ul>"
     "<li><input type='image' name='input1' value='string1value' /></li>"
     "<li><input type='image' name='input2' value='string2value' /></li>"
     "</ul>"
     "<span class='spantext'><b>Hello World 1</b></span>"
     "<span class='spantext'><b>Hello World 2</b></span>";
     HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];
     
     if (error) {
     NSLog(@"Error: %@", error);
     return;
     }
     
     HTMLNode *bodyNode = [parser body];
     
     NSArray *inputNodes = [bodyNode findChildTags:@"input"];
     
     for (HTMLNode *inputNode in inputNodes) {
     if ([[inputNode getAttributeNamed:@"name"] isEqualToString:@"input2"]) {
     NSLog(@"%@", [inputNode getAttributeNamed:@"value"]); //Answer to first question
     }
     }
     
     NSArray *spanNodes = [bodyNode findChildTags:@"span"];
     
     for (HTMLNode *spanNode in spanNodes) {
     if ([[spanNode getAttributeNamed:@"class"] isEqualToString:@"spantext"]) {
     NSLog(@"%@", [spanNode rawContents]); //Answer to second question
     }
     }
     
     [parser release];     
     
     
     */
    /*
     <tbody>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=AoG.qKvHQQXIf.ElvewzTkvXVax_;_ylu=X3oDMTFkbDMwdThkBHBvcwMxMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDNTQzOXR3bw--?s=5439.TWO" >5439.TWO</a></td><td>1ST HI-TECH ENT TWD10</td><td class="ticker_up">23.70</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=ArLZR7jfl7oHYRE8bR1wCTPXVax_;_ylu=X3oDMTFka3Y5dDh1BHBvcwMxMwRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTc4OHR3bw--?s=1788.TWO" >1788.TWO</a></td><td>HI-CLEARANCE INC TWD10</td><td class="ticker_up">81.80</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=Ags5MINX.XEUNKu2RUQa_FDXVax_;_ylu=X3oDMTFkcnZpZzZxBHBvcwMxNARzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTU2OXR3bw--?s=1569.TWO" >1569.TWO</a></td><td>BIN CHUAN ENTERPRI TWD10</td><td class="ticker_up">62.50</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=AgPjRfeqzll9AnqzO8s_4pPXVax_;_ylu=X3oDMTFnNmVtZDBuBHBvcwMxNQRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDdzcwMzQ2NHR3bw--?s=W%3A703464.TWO" >W:703464.TWO</a></td><td></td><td class="ticker_down">1.57</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=Av.Mn4r4PCbVoT4cv8wg_47XVax_;_ylu=X3oDMTFkMGNlNDBnBHBvcwMxNgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTgxNXR3bw--?s=1815.TWO" >1815.TWO</a></td><td>FULLTECH FIBER GLA TWD10</td><td class="ticker_up">23.50</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=AhZWMvAWIZ2CAE0iBvZCXeDXVax_;_ylu=X3oDMTFkZHVtYnZtBHBvcwMxNwRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTc4NXR3bw--?s=1785.TWO" >1785.TWO</a></td><td>SOLAR APPLIED MATE TWD10</td><td class="ticker_up">45.20</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=ArerglhRapB_unziJ8trcdjXVax_;_ylu=X3oDMTFkbG1jcXM2BHBvcwMxOARzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTU3MHR3bw--?s=1570.TWO" >1570.TWO</a></td><td>DE POAN PNEUMATIC TWD10</td><td>8.00</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=Anv9LlUtBrksipoWa_SkZWDXVax_;_ylu=X3oDMTFkdW5uYmQ5BHBvcwMxOQRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTMzN3R3bw--?s=1337.TWO" >1337.TWO</a></td><td>ASIA PLASTIC RECYCLING HOLDING </td><td>123.00</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=AozTpZ62FEP8zryHz6TllpXXVax_;_ylu=X3oDMTFnbmVpdnI3BHBvcwMyMARzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDdzcwMzQ3NHR3bw--?s=W%3A703474.TWO" >W:703474.TWO</a></td><td></td><td>0.64</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=AvxEUAriRrFu.z0dx8sjSyLXVax_;_ylu=X3oDMTFkZDFlY3FuBHBvcwMyMQRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTgxN3R3bw--?s=1817.TWO" >1817.TWO</a></td><td>SANITA</td><td class="ticker_down">26.80</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=Aqg.mRPlPrT9ZKpIP7uRHAfXVax_;_ylu=X3oDMTFkMDRlM3NnBHBvcwMyMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTMzOHR3bw--?s=1338.TWO" >1338.TWO</a></td><td>Hiroca</td><td class="ticker_down">100.00</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=Aia8NS7Nxo4xNWKqspqD7ZHXVax_;_ylu=X3oDMTFkcmlmNzBtBHBvcwMyMwRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTU4MHR3bw--?s=1580.TWO" >1580.TWO</a></td><td>SINMAG BAKERY MACH TWD10</td><td class="ticker_up">84.50</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=Agf6FxN6XGbr1gUnlcpb5EDXVax_;_ylu=X3oDMTFnc2JwcWs1BHBvcwMyNARzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDdzcwMzQ3OXR3bw--?s=W%3A703479.TWO" >W:703479.TWO</a></td><td></td><td class="ticker_up">0.91</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=AstQXSs86PbAms_v.BKtzQTXVax_;_ylu=X3oDMTFkc2Q4c2RmBHBvcwMyNQRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTc3N3R3bw--?s=1777.TWO" >1777.TWO</a></td><td>SYN-TECH CHEM&PHAR TWD10</td><td class="ticker_up">44.15</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=AhRVxJK0dJsKDDBx8BbdvOPXVax_;_ylu=X3oDMTFkM29zM2tiBHBvcwMyNgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDNTIzMnR3bw--?s=5232.TWO" >5232.TWO</a></td><td>EVENDATA</td><td>50.50</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=Ap.cnoMwzGk.meGUcWmhIhrXVax_;_ylu=X3oDMTFkOGdwbDMwBHBvcwMyNwRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTU4NHR3bw--?s=1584.TWO" >1584.TWO</a></td><td>S-TECH CORP TWD10</td><td class="ticker_down">31.70</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=AtfTfEd9v8NwZoRl2iHN9p_XVax_;_ylu=X3oDMTFndmxmNTUzBHBvcwMyOARzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDdzcwMzQ1OXR3bw--?s=W%3A703459.TWO" >W:703459.TWO</a></td><td></td><td>1.23</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=AhLIl68VwA0PIrQ8wGQcfX7XVax_;_ylu=X3oDMTFkZWVxOTNuBHBvcwMyOQRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTU4NnR3bw--?s=1586.TWO" >1586.TWO</a></td><td>CFTC</td><td class="ticker_down">30.00</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-odd"><td><a href="http://finance.yahoo.com/q;_ylt=AvJEhb8gh0SkK1sQZTdS7HnXVax_;_ylu=X3oDMTFkZG1yZ2dwBHBvcwMzMARzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDMTU5NHR3bw--?s=1594.TWO" >1594.TWO</a></td><td>JUKAO</td><td>20.50</td><td>Stock</td><td></td><td>TWO</td></tr>
     
     <tr class="yui-dt-even"><td><a href="http://finance.yahoo.com/q;_ylt=ApVpSlS5gDeTu4RfExIbv8HXVax_;_ylu=X3oDMTFnbDNrMWV1BHBvcwMzMQRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDdzcwMzUxNXR3bw--?s=W%3A703515.TWO" >W:703515.TWO</a></td><td></td><td class="ticker_up">0.77</td><td>Stock</td><td></td><td>TWO</td></tr></tbody>     
     
     */
    
    
  
    
    NSString *urls;
    urls=@"http://finance.yahoo.com/lookup/stocks;_ylt=AlmmFOOBaDjLY.v5nT5XBD7XVax_;_ylu=X3oDMTFicDh1YjFiBHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDZmlyc3Q-?s=1%2a+.TWO&t=S&m=ALL&r=&b=0";
    
    
    NSURL *url = [NSURL URLWithString:urls];
    
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url  
                                                cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                            timeoutInterval:30];
    NSURLResponse *urlResponse;
    NSError *error1;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest
                                                 returningResponse:&urlResponse
                                                             error:&error1];
    char *cString = (char*)[responseData bytes];
    //取出網頁資料
    NSString *string = [NSString stringWithCString:cString
                                          encoding:NSUTF8StringEncoding];    
    
    
  //  NSLog(@"string=%@",string);
    
    
    //標記:從Yahoo下載股票表格資料分解解析
    
    NSError *error = nil;
   
    NSString *html;
    html=string;
    
    HTMLParser *rawparser = [[[HTMLParser alloc] initWithString:html error:&error] autorelease];
    
    if (error) {
        NSLog(@"Error: %@", error);
        return;
    }
    
    HTMLNode *rawbodyNode = [rawparser body];
    
    //找出列  節點的開頭是tr
    NSArray *RawNodes = [rawbodyNode findChildTags:@"tr"];
    int raw=1;
    for (HTMLNode *rawNode in RawNodes) {
        //找到 class="yui-dt-even" or class="yui-dt-even"
        
        if ([[rawNode getAttributeNamed:@"class"] isEqualToString:@"yui-dt-odd"] || [[rawNode getAttributeNamed:@"class"] isEqualToString:@"yui-dt-even"] ) {
            
             NSLog(@"列%i 找到列的原始資料=%@",raw, [rawNode rawContents]); 
             
            //針對每個列 拆出行 column
            
            HTMLParser *columnparser = [[HTMLParser alloc] initWithString:[rawNode rawContents] error:&error];
            HTMLNode *columnbodyNode = [columnparser body];
            //找出行  節點的開頭是td           
            NSArray *ColumnNodes = [columnbodyNode findChildTags:@"td"]; 
           
            int column=1;
           
            //NSString *codes;
             
            //NSString *types;
            //NSString *industrys;
            //NSString *exchanges;
            
            for (HTMLNode *columnNode in ColumnNodes) {
                             
                
                
                if (column==1) { 
                    //symbol
                    
                    //第一行是 代號名稱 並且裡面含有url 所以要再度解析
                    
                    HTMLParser *codeparser = [[HTMLParser alloc] initWithString:[columnNode rawContents] error:&error];
                    HTMLNode *codebodyNode = [codeparser body];
                    //股票代碼藏在更深入一層的 <a>
                    NSArray *codeNodes = [codebodyNode findChildTags:@"a"]; 
                    
                    for (HTMLNode *codeNode in codeNodes) {
                        
                       NSLog(@"code=%@",[codeNode contents]); //contents 表示不含有html標籤<>  ,rawContents 含有標簽                        
                                                
                    }
                    [codeparser release];
                }
                else if(column==2){
                    //name
                                                           
                    
                }              
                else if(column==3){
                    //Last price
                    
                    
                    
                }         
                else if(column==4){
                    //Type
                    /*
                    if ([columnNode contents] == nil) {
                        types=@"N/A";
                    }
                    else{
                        types=[columnNode contents]; 
                    }
                    */
                    
                }                     
                else if(column==5){
                    //Industry
                    /*
                    if ([columnNode contents] == nil) {
                        industrys=@"Undifine";
                    }
                    else{
                        industrys=[columnNode contents]; 
                    }
                    */
                    
                }                     
                else if(column==6){
                    //Exchange
                    /*
                    if ([columnNode contents] == nil) {
                        exchanges=@"N/A";
                    }
                    else{
                        exchanges=[columnNode contents]; 
                    }
                    */
                    
                }                     
                
                NSLog(@"行%i=%@",column,[columnNode contents]);                
                
                column=column+1;
                
                
            }
                          
             
            [columnparser release];            
             raw=raw+1;
        }
       
        else{
            NSLog(@"不是列的原始資料=%@", [rawNode rawContents]);             
            
        }
    
    }
    
    

}
-(void)getAlbumInfo
{
   
    
    //初始化記憶體 用來記載下載分析後的資料陣列
    
    code_array=[[NSMutableArray alloc] init];
    name_array=[[NSMutableArray alloc] init];    
    type_array=[[NSMutableArray alloc] init];
    industry_array=[[NSMutableArray alloc] init];
    exchange_array=[[NSMutableArray alloc] init];    
    
    NSMutableArray *type;
    type=[[[NSMutableArray alloc] init] autorelease];
    
    
    //使用在url 的國家別
    // NSString *country;
    //使用在url 上的第一個字母或數字   
    NSMutableArray *A_Z_0_9;    
    A_Z_0_9=[[[NSMutableArray alloc] init] autorelease];
    
    NSString *number_abc;
    
    
    //選擇要取出的設定
    //如果是空白字串 表示要搜尋美國交易所
    NSMutableArray *loop_exchange_array;
    loop_exchange_array=[[[NSMutableArray alloc] init] autorelease];
    
    
    
    //標記:Add Target need Program
    //標記:從Yahoo下載所有股票基本資料
    NSString *DisplayName;
    DisplayName=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]; 
    
    NSString *getMarket;//US :表示只取出美國與加拿大市場 ALL:表示取出全球市場同步搜尋
    
     
    
    if ([DisplayName isEqualToString:@"TW"]) {
        
        
             
        
    } 
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_iStock Global"]  ) {
        //西班牙市場
        [loop_exchange_array addObject:@"BC"];
        [loop_exchange_array addObject:@"BI"]; 
        [loop_exchange_array addObject:@"MF"];
        [loop_exchange_array addObject:@"MC"]; 
        [loop_exchange_array addObject:@"MA"]; 
        
        number_abc=@"abc_abc";    
        [type addObject:@"etfs"];
        [type addObject:@"stocks"];    
        [type addObject:@"funds"];  
        getMarket=@"ALL";        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_ETF"]  ) {
        //美國ＥＴＦ
         [loop_exchange_array addObject:@""];  
         [type addObject:@"etfs"];
         number_abc=@"abc"; 
         getMarket=@"US";
        //getMarket=@"ALL"; 
        
       // 此段網址可以取出所有美國ＥＴＦ分類 http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=1258        
        
    }	    
    
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_NZ"]  ) {
        //***紐西蘭市場
        [loop_exchange_array addObject:@"NZ"];
        [loop_exchange_array addObject:@"AX"];        
        number_abc=@"number+abc";    
        [type addObject:@"stocks"];  
         getMarket=@"ALL";        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_HK"]  ) {
      //香港市場
        [loop_exchange_array addObject:@"HK"];
        number_abc=@"number_number";    
        [type addObject:@"stocks"];    
          getMarket=@"ALL";                        
        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_CH"]  ) {
        
                    
        
    }	
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_US"]  ) {
        //美國STOCKS
        [loop_exchange_array addObject:@""];  
        [type addObject:@"stocks"];
        number_abc=@"abc_abc"; 
        getMarket=@"US";                  
        
    }		        
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_UK"]  ) {
       //***英國 11/4
        [loop_exchange_array addObject:@"L"];
        number_abc=@"abc";        
        [type addObject:@"stocks"];            
        getMarket=@"ALL";          
        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_CN"]  ) {
        //***加拿大
        [loop_exchange_array addObject:@"TO"]; 
        [loop_exchange_array addObject:@"V"];
        number_abc=@"abc";        
        [type addObject:@"stocks"];            
        getMarket=@"ALL";           
        
        
    }	
    
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_AX"]  ) {
        //***澳洲 11/4
        [loop_exchange_array addObject:@"AX"];
        number_abc=@"abc";        
        [type addObject:@"stocks"];            
        getMarket=@"ALL";        
        
    }       
    
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_KS"]  ) {
        
                
        
    }	  
        
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_SI"]  ) {
                   
        
    }                       
   
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_GR"]  ) {
        
                    
        
    }   
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_PA"]  ) {
        
                   
        
    }   
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_MI"]  ) {
     //義大利   
        [loop_exchange_array addObject:@"MI"];        
        number_abc=@"abc_abc";         
        [type addObject:@"etfs"];
        [type addObject:@"stocks"];    
        [type addObject:@"funds"];
         getMarket=@"ALL";         
        
    }      
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_INDIA"]  ) {
        //***印度市場的交易所與ＢＬＯＯＭＢＥＲＧ的是不同,主要是因為ＢＬＯＯＭＢＥＲＧ將太長的字串縮減
        //印度
        [loop_exchange_array addObject:@"BO"];
        [loop_exchange_array addObject:@"NS"];        
        number_abc=@"abc_abc"; 
        [type addObject:@"stocks"];         
         getMarket=@"ALL"; 
    }	
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_SA"]  ) {
        //***巴西
        [loop_exchange_array addObject:@"SA"];    
        number_abc=@"abc_abc";        
        [type addObject:@"stocks"];           
         getMarket=@"ALL"; 
    }	
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_MX"]  ) {
        //***墨西哥
        [loop_exchange_array addObject:@"MX"];    
        number_abc=@"abc";        
        [type addObject:@"stocks"];            
         getMarket=@"ALL"; 
    }	    
    
    else{
        //GlobalＥＴＦ
        [loop_exchange_array addObject:@""];  
        [type addObject:@"etfs"];
        number_abc=@"abc"; 
        getMarket=@"ALL";           
        
  
        
    
    }	            
    
        
    
    //準備字串
    if ([number_abc isEqualToString:@"abc"]) {
        [A_Z_0_9 addObject:@"a"];
        [A_Z_0_9 addObject:@"b"];    
        [A_Z_0_9 addObject:@"c"];
        [A_Z_0_9 addObject:@"d"];    
        [A_Z_0_9 addObject:@"a"];
        [A_Z_0_9 addObject:@"f"];    
        [A_Z_0_9 addObject:@"g"];
        [A_Z_0_9 addObject:@"h"]; 
        [A_Z_0_9 addObject:@"i"];
        [A_Z_0_9 addObject:@"j"];    
        [A_Z_0_9 addObject:@"k"];
        [A_Z_0_9 addObject:@"l"]; 
        [A_Z_0_9 addObject:@"m"];
        [A_Z_0_9 addObject:@"n"];    
        [A_Z_0_9 addObject:@"o"];
        [A_Z_0_9 addObject:@"p"];    
        [A_Z_0_9 addObject:@"q"];
        [A_Z_0_9 addObject:@"r"];    
        [A_Z_0_9 addObject:@"s"];
        [A_Z_0_9 addObject:@"t"];    
        [A_Z_0_9 addObject:@"u"];
        [A_Z_0_9 addObject:@"v"];    
        [A_Z_0_9 addObject:@"w"];
        [A_Z_0_9 addObject:@"x"];    
        [A_Z_0_9 addObject:@"y"];
        [A_Z_0_9 addObject:@"z"];
    }
    else if([number_abc isEqualToString:@"number"] ){
        [A_Z_0_9 addObject:@"0"];
        [A_Z_0_9 addObject:@"1"];    
        [A_Z_0_9 addObject:@"2"];
        [A_Z_0_9 addObject:@"3"];    
        [A_Z_0_9 addObject:@"4"];
        [A_Z_0_9 addObject:@"5"];    
        [A_Z_0_9 addObject:@"6"];
        [A_Z_0_9 addObject:@"7"]; 
        [A_Z_0_9 addObject:@"8"];
        [A_Z_0_9 addObject:@"9"];    
        
        
    }
    else if([number_abc isEqualToString:@"number+abc"] ){
        [A_Z_0_9 addObject:@"0"];
        [A_Z_0_9 addObject:@"1"];    
        [A_Z_0_9 addObject:@"2"];
        [A_Z_0_9 addObject:@"3"];    
        [A_Z_0_9 addObject:@"4"];
        [A_Z_0_9 addObject:@"5"];    
        [A_Z_0_9 addObject:@"6"];
        [A_Z_0_9 addObject:@"7"]; 
        [A_Z_0_9 addObject:@"8"];
        [A_Z_0_9 addObject:@"9"];
        
        [A_Z_0_9 addObject:@"a"];
        [A_Z_0_9 addObject:@"b"];    
        [A_Z_0_9 addObject:@"c"];
        [A_Z_0_9 addObject:@"d"];    
        [A_Z_0_9 addObject:@"e"];
        [A_Z_0_9 addObject:@"f"];    
        [A_Z_0_9 addObject:@"g"];
        [A_Z_0_9 addObject:@"h"]; 
        [A_Z_0_9 addObject:@"i"];
        [A_Z_0_9 addObject:@"j"];    
        [A_Z_0_9 addObject:@"k"];
        [A_Z_0_9 addObject:@"l"]; 
        [A_Z_0_9 addObject:@"m"];
        [A_Z_0_9 addObject:@"n"];    
        [A_Z_0_9 addObject:@"o"];
        [A_Z_0_9 addObject:@"p"];    
        [A_Z_0_9 addObject:@"q"];
        [A_Z_0_9 addObject:@"r"];    
        [A_Z_0_9 addObject:@"s"];
        [A_Z_0_9 addObject:@"t"];    
        [A_Z_0_9 addObject:@"u"];
        [A_Z_0_9 addObject:@"v"];    
        [A_Z_0_9 addObject:@"w"];
        [A_Z_0_9 addObject:@"x"];    
        [A_Z_0_9 addObject:@"y"];
        [A_Z_0_9 addObject:@"z"];        
        
        
    }
    else if([number_abc isEqualToString:@"abc_abc"] ){
        
        NSMutableArray *a_z;
        a_z=[[NSMutableArray alloc] init];
        
        
        [a_z addObject:@"a"];
        [a_z addObject:@"b"];    
        [a_z addObject:@"c"];
        [a_z addObject:@"d"];    
        [a_z addObject:@"e"];
        [a_z addObject:@"f"];    
        [a_z addObject:@"g"];
        [a_z addObject:@"h"]; 
        [a_z addObject:@"i"];
        [a_z addObject:@"j"];    
        [a_z addObject:@"k"];
        [a_z addObject:@"l"]; 
        [a_z addObject:@"m"];
        [a_z addObject:@"n"];    
        [a_z addObject:@"o"];
        [a_z addObject:@"p"];    
        [a_z addObject:@"q"];
        [a_z addObject:@"r"];    
        [a_z addObject:@"s"];
        [a_z addObject:@"t"];    
        [a_z addObject:@"u"];
        [a_z addObject:@"v"];    
        [a_z addObject:@"w"];
        [a_z addObject:@"x"];    
        [a_z addObject:@"y"];
        [a_z addObject:@"z"];        
        
        for (NSString *a_z_1 in a_z) {
            //一個字母
             [A_Z_0_9 addObject: a_z_1 ];
        }
       
        for (NSString *a_z_1 in a_z) {
            for (NSString *a_z_2 in a_z) {
                //兩個字母
                [A_Z_0_9 addObject:[NSString stringWithFormat:@"%@%@",a_z_1,a_z_2]];
            }        
        }
        
    }
    else if([number_abc isEqualToString:@"number_number"] ){
        
        NSMutableArray *a_z;
        a_z=[[NSMutableArray alloc] init];
        
        
        [a_z addObject:@"0"];
        [a_z addObject:@"1"];    
        [a_z addObject:@"2"];
        [a_z addObject:@"3"];    
        [a_z addObject:@"4"];
        [a_z addObject:@"5"];    
        [a_z addObject:@"6"];
        [a_z addObject:@"7"]; 
        [a_z addObject:@"8"];
        [a_z addObject:@"9"];    
        
        
        for (NSString *a_z_1 in a_z) {
            for (NSString *a_z_2 in a_z) {
                NSLog(@"%@%@",a_z_1,a_z_2);
                [A_Z_0_9 addObject:[NSString stringWithFormat:@"%@%@",a_z_1,a_z_2]];
            }        
        }
        
    }    
    
    int pre_total_count;
    pre_total_count=0;
   
    BOOL yesloop;
    yesloop=YES;
    //進入循環
    for (int lq=0; lq<10 && yesloop==YES; lq++) {
        //循環兩次來避免可能因為網路斷線或是漏掉的網頁
        for (NSString *types in type) {
            
            for (NSString *lca in loop_exchange_array ) {
                
                for (NSString *charr in A_Z_0_9 ) {
                    BOOL LOOPRUN;
                    LOOPRUN=YES;
                    for (int ind=0; ind<50 && LOOPRUN==YES; ind++) {
                        NSString *urls=@"";
                        //特別注意跳脫字元% 要用%%表示
                        
                        NSString *search;
                        if ([lca isEqualToString:@""]) {
                            search=[NSString stringWithFormat:@"%@%%2a&t",charr ];                    
                            
                        }
                        else{
                            search=[NSString stringWithFormat:@"%@%%2a+.%@&t",charr,lca];
                        }
                        
                        
                        //不同形態
                        if ([types isEqualToString:@"all"]) {
                            //all
                            if (ind==0) {
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/all;_ylt=AlmmFOOBaDjLY.v5nT5XBD7WVax_;_ylu=X3oDMTFicDh1YjFiBHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDZmlyc3Q-?s=%@=A&m=@%&r=&b=0",search,getMarket];
                                                                                                
                                
                                
                                
                            }
                            else{
                               urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/all;_ylt=Atq6W9moYTB8N_8nsiJQ6NfWVax_;_ylu=X3oDMTFhazBlZXI2BHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDbmV4dA--?s=%@=A&m=%@&r=&b=%i",search,getMarket,ind*20];   
                                                               
                                
                                
                            }
                            
                            
                            
                        }
                        else if ([types isEqualToString:@"stocks"]) {
                            //stocks
                            if (ind==0) {
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/stocks;_ylt=AlmmFOOBaDjLY.v5nT5XBD7XVax_;_ylu=X3oDMTFicDh1YjFiBHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDZmlyc3Q-?s=%@=S&m=%@&r=&b=0",search,getMarket];             
                                
                            }
                            else{
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/stocks;_ylt=Atq6W9moYTB8N_8nsiJQ6NfXVax_;_ylu=X3oDMTFhazBlZXI2BHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDbmV4dA--?s=%@=S&m=%@&r=&b=%i",search,getMarket,ind*20];                
                                
                            }
                            
                            
                            
                            
                        }                    
                        else if ([types isEqualToString:@"etfs"]) {
                            //etfs
                            if (ind==0) {
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/etfs;_ylt=Am0.P7iN6nNFGHWLdaRcUzfbVax_;_ylu=X3oDMTFicTlrcTlnBHBvcwMyNARzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDZmlyc3Q-?s=%@=E&m=%@&r=&b=0",search,getMarket];             
                                
                            }
                            else{
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/etfs;_ylt=Atq6W9moYTB8N_8nsiJQ6NfbVax_;_ylu=X3oDMTFhazBlZXI2BHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDbmV4dA--?s=%@=E&m=%@&r=&b=%i",search,getMarket,ind*20];                
                                
                            }
                            
                            
                            
                            
                        }                                               
                        else if ([types isEqualToString:@"indices"]) {
                            //indices
                            if (ind==0) {
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/indices;_ylt=AkDZtsqGtNKGd6aGF1NFcNzbVax_;_ylu=X3oDMTFjdGY5NWQ1BHBvcwM1BHNlYwN5ZmlTeW1ib2xMb29rdXBSZXN1bHRzBHNsawNpbmRpY2Vz?s=%@=I&m=%@&r=",search,getMarket];             
                                
                            }
                            else{
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/indices;_ylt=Atq6W9moYTB8N_8nsiJQ6NfaVax_;_ylu=X3oDMTFhazBlZXI2BHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDbmV4dA--?s=%@=I&m=%@&r=&b=%i",search,getMarket,ind*20];                
                                
                            }
                            
                            
                            
                            
                        }                              
                        else if ([types isEqualToString:@"funds"]) {
                            //funds
                            if (ind==0) {
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/funds;_ylt=AlmmFOOBaDjLY.v5nT5XBD7YVax_;_ylu=X3oDMTFicDh1YjFiBHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDZmlyc3Q-?s=%@=M&m=%@&r=&b=0",search,getMarket];             
                                
                            }
                            else{
                                urls=[NSString stringWithFormat:@"http://finance.yahoo.com/lookup/funds;_ylt=Atq6W9moYTB8N_8nsiJQ6NfYVax_;_ylu=X3oDMTFhazBlZXI2BHBvcwMzMgRzZWMDeWZpU3ltYm9sTG9va3VwUmVzdWx0cwRzbGsDbmV4dA--?s=%@=M&m=%@&r=&b=%i",search,getMarket,ind*20];                
                                
                            }
                            
                            
                            
                            
                        }                              
                        
                        
                        
                        
                        NSURL *url = [NSURL URLWithString:urls];
                        
                        
                        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url  
                                                                    cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                                                timeoutInterval:30];
                        NSURLResponse *urlResponse;
                        NSError *error;
                        NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest
                                                                     returningResponse:&urlResponse
                                                                                 error:&error];
                        char *cString = (char*)[responseData bytes];
                        //取出網頁資料
                        NSString *string = [NSString stringWithCString:cString
                                                              encoding:NSUTF8StringEncoding];
                        
                        NSLog(@"loop=%i ,type=%@ ,exchange=%@ ,char=%@ index=%i",lq,types,lca,charr,ind*20);
                        NSLog(@"url=%@",url);            
                        //網頁資料處理
                        LOOPRUN=[self showSongList:string];
                        
                    }
                }
                
                
            }
            
            
        }
        if (pre_total_count==[code_array count]) {
            yesloop=NO;
            NSLog(@"loop=%i,******nNO LOOP pre=%i code_array=%i",lq,pre_total_count,[code_array count]);
        }
        else{
            NSLog(@"loop=%i,******YES LOOP pre=%i code_array=%i",lq,pre_total_count,[code_array count]);

        }
        pre_total_count=[code_array count];
    }
    
    
    
    //取出資料結束後的轉出成文字檔
    NSMutableString *outs = [[[NSMutableString alloc] init] autorelease];
    
    for (int i=0 ; i<[code_array count]; i++) {
        [outs appendFormat:@"%@\t%@\t%@\t%@\t%@\n",[code_array objectAtIndex:i] ,[name_array objectAtIndex:i],[type_array objectAtIndex:i],[industry_array objectAtIndex:i],[exchange_array objectAtIndex:i]];
    }
    
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *dir = [paths objectAtIndex:0];
    NSString *filePathw;
    filePathw = [[NSString alloc] initWithString:[dir stringByAppendingPathComponent:[NSString stringWithFormat: @"ALL_Data_%@.txt",DisplayName]]];
    
    [outs writeToFile:filePathw atomically:YES encoding:NSUTF8StringEncoding error: nil  ];
    
    
    [filePathw release];    
    
    NSLog(@"總計分析取出檔數=%i",[code_array count]);
    
    
    UIAlertView *av;
	av=[[UIAlertView alloc]initWithTitle:@"訊息" message:@"下載取出資料結束" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
    [av show];
    [av release];    
    
}


#pragma mark -
#pragma mark  上傳奇狐與xxtradexx資料庫
-(void)upload_action:(NSString *)upload_type {
	//上傳奇狐檔案
	//建立目錄
	NSString *path;
	path=[NSString stringWithFormat:@"Documents/%@",@"chiefox"];			
	
	NSFileManager *filemanager=[NSFileManager defaultManager];
	NSString *newdirpath=[NSHomeDirectory() stringByAppendingPathComponent:path];			
	[filemanager createDirectoryAtPath:newdirpath withIntermediateDirectories:YES attributes:nil error:nil];
	
	
	DataObject *ob;
	
	NSDateFormatter* df = [[NSDateFormatter alloc]init];
	[df setDateFormat:@"M/dd/yyyy"];
	    
    
	NSDateFormatter* df1 = [[NSDateFormatter alloc]init];
	[df1 setDateFormat:@"yyyyMMdd"];			
	
	NSDateFormatter* df_xxtradexx = [[NSDateFormatter alloc]init];
    [df_xxtradexx setDateFormat:@"yyyy/M/d"];	
	
    
    NSString *dates;
	NSString *dates_xxtradexx;
	
	NSArray *symbola;
	
	NSString *opens;
	NSString *highs;
	NSString *lows;
	NSString *closes;
	NSString *vols;
	NSString *symbols_xxtradexx;
	NSString *symbols_yahoo;	
	NSString *symbol_chiefox;	
	
	NSString *firstDates;
	NSString *firstSymbol=@"";
	NSString *country;
	
	BOOL havefirst;
	havefirst=NO;
	
	int writecount_chiefox=0; //寫入數目
	int fileindex_chiefox;  //檔案排名
	fileindex_chiefox=0;
	
	int writecount_xxtradexx=0;
	int fileindex_xxtradexx;
	fileindex_xxtradexx=0;	
	
	
	NSString *ws_chiefox;
	NSString *ws_xxtradexx;	
	
	NSString *newdirpath_File;			//排序
	NSArray *sortob ;
	sortob= [download_data_obj sortedArrayUsingFunction:comparator_Symbola_UP  context:nil];		
	
	//奇狐檔案路徑
	uploadpathfile_chiefox=[[NSMutableArray alloc] init];
	//xxtradexx 歷史資料補充
	uploadpathfile_xxtradexx=[[NSMutableArray alloc] init];
	 
	for (int i=0 ; i<[sortob count]; i++) {
		
		
		
		ob=[sortob objectAtIndex:i];			
        
        symbola=[ob.symbol componentsSeparatedByString:@"."];				
        symbols_xxtradexx=ob.symbol_xxtradexx;
        symbols_yahoo=ob.symbol;		
        
        
        //標記:增加一個市場，可以盤後回補當日資料 3 奇狐國家碼        
        //標記:Add Target need Program 奇狐資料國家碼        
        
        if([symbola count]==1) {
            symbol_chiefox=[@"US" stringByAppendingString: ob.symbol];	
            country=@"US";
            
        }
        else {
            if ([[symbola objectAtIndex:1] isEqualToString:@"HK"] ) {
                symbol_chiefox=[@"HK" stringByAppendingString: [symbola objectAtIndex:0]];					
                country=@"HK";
            } 
            else if ([[symbola objectAtIndex:1] isEqualToString:@"TW"] || [[symbola objectAtIndex:1] isEqualToString:@"TWO"]) {
                symbol_chiefox=[@"TT" stringByAppendingString: [symbola objectAtIndex:0]];					
                country=@"TT";
            }	
            else if ([[symbola objectAtIndex:1] isEqualToString:@"AX"]  ) {
                symbol_chiefox=[@"AU" stringByAppendingString: [symbola objectAtIndex:0]];					
                country=@"AU";
            }	            
            else if ([[symbola objectAtIndex:1] isEqualToString:@"SI"]  ) {
                symbol_chiefox=[@"SI" stringByAppendingString: [symbola objectAtIndex:0]];					
                country=@"SI";
            }	               
            
            else {
                symbol_chiefox=[@"NO" stringByAppendingString: [symbola objectAtIndex:0]];								
                country=@"NO";
                
            }
            
            
            
        }
               
        
        
        
       
		
		//NSLog(@"ob.tradedate=%@",ob.tradedate);
		
		NSDate *theDate = [[NSDateFormatter yahooDailyDateFormatter] dateFromString:ob.tradedate];			
		
		dates = [df stringFromDate:theDate];				
		dates_xxtradexx=[[df_xxtradexx stringFromDate:theDate] stringByAppendingString:@"_0:0"] ;
		//NSLog(@"dates_xxtradexx=%@",dates_xxtradexx);		
		
        
        opens=ob.s_open;
		highs=ob.s_high;
		lows=ob.s_low;
		closes=ob.lastprice;
		vols=ob.volume_yahoo;
		
		//判斷是否有ＮＡ值
		if ([opens isEqualToString:@"N/A"] && ![closes isEqualToString:@"N/A"] && [closes floatValue]>0) {
			opens=closes;
		}
		if ([highs isEqualToString:@"N/A"] && ![closes isEqualToString:@"N/A"] && [closes floatValue]>0) {
			highs=closes;
		}	
		if ([lows isEqualToString:@"N/A"] && ![closes isEqualToString:@"N/A"]  && [closes floatValue]>0) {
			lows=closes;
		}				
		
		
		if ([closes floatValue] >0  &&  dates !=nil ) {
			if (havefirst==NO) {
				havefirst=YES;
				
				ws_chiefox=@"";						 
				writecount_chiefox=0;						 
				
				ws_xxtradexx=@"";						 
				writecount_xxtradexx=0;				
				
				firstDates = [df1 stringFromDate:theDate];	
				firstSymbol=country;
			}
			
			writecount_chiefox=writecount_chiefox+1;
			ws_chiefox=[ws_chiefox stringByAppendingFormat:@"%@\t%@\t%@\t%@\t%@\t%@\t%@\r\n",symbol_chiefox,dates,opens,highs,lows,closes,vols];	
			//NSLog(@"%@",ws_chiefox);
			writecount_xxtradexx=writecount_xxtradexx+1;
			//NSLog(@"%@,%@,%@,%@,%@,%@,%i,%i,%@,%@,%@,%@,0,0",symbols_yahoo,symbols_xxtradexx,opens,highs,lows,closes,0,0,vols,dates_xxtradexx,dates_xxtradexx,dates_xxtradexx);
			ws_xxtradexx=[ws_xxtradexx stringByAppendingFormat:@"%@,%@,%@,%@,%@,%@,%i,%i,%@,%@,%@,%@,0,0\r\n",symbols_yahoo,symbols_xxtradexx,opens,highs,lows,closes,0,0,vols,dates_xxtradexx,dates_xxtradexx,dates_xxtradexx];	
			
		}
		
		if (writecount_chiefox>=700) {
			//檔案名稱與路徑
			newdirpath_File=[newdirpath stringByAppendingFormat:@"/data_i%@%i_%@_ok.txt",firstSymbol,fileindex_chiefox,firstDates];
			
			//寫入檔案
			[ws_chiefox writeToFile:newdirpath_File atomically:YES encoding:NSUTF8StringEncoding error:nil];
			[uploadpathfile_chiefox addObject:[newdirpath_File mutableCopy]];
			
			//歸0
			//havefirst=NO;
			ws_chiefox=@"";						 
			writecount_chiefox=0;					
			fileindex_chiefox=fileindex_chiefox+1; 					
		}
		
		if (writecount_xxtradexx>=100) {
			//檔案名稱與路徑
			newdirpath_File=[newdirpath stringByAppendingFormat:@"/raeltime_xq_%i.csv" ,fileindex_xxtradexx];
			
			//寫入檔案
           
			[ws_xxtradexx writeToFile:newdirpath_File atomically:YES encoding:NSUTF8StringEncoding error:nil];
			[uploadpathfile_xxtradexx addObject:[newdirpath_File mutableCopy]];
			
			//歸0
			//havefirst=NO;
			ws_xxtradexx=@"";						 
			writecount_xxtradexx=0;					
			fileindex_xxtradexx=fileindex_xxtradexx+1; 					
		}
		
		
	}
	 
	//chiefox
	//檔案名稱與路徑
	newdirpath_File=[newdirpath stringByAppendingFormat:@"/data_i%@%i_%@_ok.txt",firstSymbol,fileindex_chiefox,firstDates];
	 		
	//寫入檔案
	[ws_chiefox writeToFile:newdirpath_File atomically:YES encoding:NSUTF8StringEncoding error:nil];
	
	[uploadpathfile_chiefox addObject: newdirpath_File  ];		
	
	//xxtradexx
	//檔案名稱與路徑
	newdirpath_File=[newdirpath stringByAppendingFormat:@"/raeltime_xq_%i.csv" ,fileindex_xxtradexx];
	
				
	//寫入檔案
	[ws_xxtradexx writeToFile:newdirpath_File atomically:YES encoding:NSUTF8StringEncoding error:nil];
	
	[uploadpathfile_xxtradexx addObject: newdirpath_File  ];	
	
	[df release];	
	[df1 release];	
	[df_xxtradexx release];
	
	if ([uploadpathfile_chiefox count]>0) {
		//開始傳送資料
		//階段一上傳至 /xxtradexx/webroot/chiefoxdata/
		//階段二上傳至 /xxtradexx/webroot/database/temp_xq/	
		//階段三將上傳至 temp_xq 資料進行伺服器上的匯入至遠端資料庫內
		
		ui_chiefox=0;	
		ui_xxtradexx=0;
		ui_xxtradexx_url=0;
		
        if ([upload_type isEqualToString:@"FTP"]) {
            
            //階段一開始ftp
             [self upload_mutarray_file_path:[uploadpathfile_chiefox objectAtIndex:ui_chiefox] server_path:@"/xxtradexx/webroot/chiefoxdata/"];            
        }
        else if([upload_type isEqualToString:@"HTTP"]){
            //階段一開始http
            http_upload_filename= [[uploadpathfile_chiefox objectAtIndex:ui_chiefox] retain];       
            [self upload_mutarray_file_path_http1:[uploadpathfile_chiefox objectAtIndex:ui_chiefox]  ];               
        }
        record_upload_type=upload_type;       
	
	
             
        
    }
	
	
	
	
	
	 
}


#pragma mark -
#pragma mark  按鈕轉換
-(void)switchChange:(id) sender{
	
	UISwitch *onoff = (UISwitch *) sender;	
	
	
	switch (onoff.tag) {
		case 100:{
			//搜尋是否要使用名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[NSNumber numberWithBool: onoff.on]  forKey:@"isKDindicator"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			 
			
			break;
		}
			
			
		default:
			break;
	}
	
	
	[myTable reloadData];
	
	
}




#pragma mark -
#pragma mark  策略選擇器
/*
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
	switch (component) {
		case 0:
			return 50;
			break;
		case 1:
			return 75;
			break;		
		case 2:
			return 75;
			break;		
		case 3:
			return 55;
			break;			
			
		default:
			break;
	}
	return 0;	
	
	
	
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
	return 100;
}
*/
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
	return 3;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
	switch (component) {
		case 0:
			return [picka1 count];
			break;
		case 1:
			return [picka2 count];
			break;			
		case 2:
			return [picka3 count];
			break;
	 
			
			 
	}
	return 0;
	
	
	
}
//客制化  pickerView 欄位
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
	UILabel *retval = (id)view;
	if (!retval) {
		retval= [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 4.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)] autorelease];
	    [retval setBackgroundColor:[UIColor clearColor]];
	}
	
	retval.numberOfLines=3;
	retval.font = [UIFont systemFontOfSize:12];
	retval.textAlignment=UITextAlignmentCenter;
	switch (component) {
		case 0:
			retval.text = [picka1 objectAtIndex:row];
			break;
		case 1:
			retval.text = [picka2 objectAtIndex:row];
			break;			
		case 2:
			retval.text = [picka3 objectAtIndex:row];
			break;
		 		
			
	}
	
	
	
	
	
	
	return retval;
}



- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
	
	 
	switch (component) {
		case 0:
			return [picka1 objectAtIndex:row];
			break;
		case 1:
			return  [picka2 objectAtIndex:row]   ;
			break;			
		case 2:
			return [picka3 objectAtIndex:row];
			break;
		 	
			
	}
	return nil;	
	
	
	
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
	
	
	switch (component) {
		 case 0:{
			 
			 NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			 [prefs setObject:[NSNumber numberWithInteger: row] forKey:@"tableR0" ];
			 [prefs synchronize];				 
			
			 [myTable reloadData];
			 
			 break;
		 }
		case 1:{
			
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[NSNumber numberWithInteger: row] forKey:@"tableR1" ];
			[prefs synchronize];				 
			
			[myTable reloadData];
			
			break;
		}
		case 2:{
			
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[NSNumber numberWithInteger: row] forKey:@"tableR2" ];
			[prefs synchronize];				 
			
			[myTable reloadData];
			
			break;
		}
			
			
		 default:
			 break;
	 }
	
}






- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


#pragma mark -
#pragma mark  ftp上傳檔案
-(void) upload_mutarray_file_path:(NSString *)filePaths server_path:(NSString *)serverpaths{
	
        
    
       //ftp 新增的部份	
	    S7FTPRequest *ftpRequest ;	
		
		ftpRequest= [[S7FTPRequest alloc] initWithURL:
					 [NSURL URLWithString:@"ftp://ftps2.brinkster.com/"]
										 toUploadFile:filePaths];
		
		ftpRequest.username = @"BRINKSTER\\xxtradexx"; //名稱
		ftpRequest.password = @"qwerty";
		ftpRequest.server_path=serverpaths;
		ftpRequest.delegate = self;
		ftpRequest.didFinishSelector = @selector(uploadFinished:);
		ftpRequest.didFailSelector = @selector(uploadFailed:);
		ftpRequest.willStartSelector = @selector(uploadWillStart:);
		ftpRequest.didChangeStatusSelector = @selector(requestStatusChanged:);
		ftpRequest.bytesWrittenSelector = @selector(uploadBytesWritten:);
		[ftpRequest startRequest];				
		
		  	
	
	

}

#pragma mark -
#pragma mark  http post上傳檔案
-(void) upload_mutarray_file_path_http1:(NSString *)filePaths  {
	
    
    
    
    
    
    
    //http 上傳檔案的核心程式碼
    [[EPUploader alloc] initWithURL:[NSURL URLWithString:@"http://www.xxtradexx.com/uploader_chiefoxdata.php?"  ]
                           filePath:filePaths
                           delegate:self
                       doneSelector:@selector(onUploadDone:)
                      errorSelector:@selector(onUploadError:)];      
    
    		
    
}
-(void) upload_mutarray_file_path_http2:(NSString *)filePaths  {
	
    
    //http 上傳檔案的核心程式碼
    [[EPUploader alloc] initWithURL:[NSURL URLWithString:@"http://www.xxtradexx.com/database/uploader_temp_xq.php?"  ]
                           filePath:filePaths
                           delegate:self
                       doneSelector:@selector(onUploadDone:)
                      errorSelector:@selector(onUploadError:)];      
    
    
    
}
 
#pragma mark -
#pragma mark  http post 回應事件

-(void)onUploadDone:(id)non {
    NSArray * Timestamp_array=[http_upload_filename componentsSeparatedByString:@"/"]; 
    
    NSString *filename;
    
    if ([Timestamp_array count]>0) {
        filename=[Timestamp_array objectAtIndex:[Timestamp_array count]-1];
    }
    else{
        filename=http_upload_filename;
        
    }
    
    upload_Tabel_Caption_HTTP= [filename copy]  ;
	
    [myTable reloadData];    
	 
	
	//[request release]; //增加此行會當機
	
	ui_chiefox=ui_chiefox+1;//因為開始使已經從0開始
	
	if ([uploadpathfile_chiefox count]>ui_chiefox) {
		//尚未全部傳遞結束 
		//第一階段上傳至奇狐專用的整批檔案
		//[self upload_mutarray_file_path:[uploadpathfile_chiefox objectAtIndex:ui_chiefox] server_path:@"/xxtradexx/webroot/chiefoxdata/"];
	    http_upload_filename=  [[uploadpathfile_chiefox objectAtIndex:ui_chiefox] retain] ;          
        [self upload_mutarray_file_path_http1:[uploadpathfile_chiefox objectAtIndex:ui_chiefox]  ];     
    }
	else{
		//第二階段上傳至歷史資料庫資料
		if ([uploadpathfile_xxtradexx count]>ui_xxtradexx) {
            http_upload_filename=  [[uploadpathfile_xxtradexx objectAtIndex:ui_xxtradexx] retain] ;          
            
            [self upload_mutarray_file_path_http2:[uploadpathfile_xxtradexx objectAtIndex:ui_xxtradexx]   ]; 			
            // [self upload_mutarray_file_path:[uploadpathfile_xxtradexx objectAtIndex:ui_xxtradexx] server_path:@"/xxtradexx/webroot/database/temp_xq/"];
			
            
            ui_xxtradexx=ui_xxtradexx+1;
			
		}
		else {
			//階段三開始
			NSString *urls;
			urls=@"";
			urls=[urls stringByAppendingFormat: @"http://www.xxtradexx.com/database/import_data_xq.aspx?ifaftclose=1&filename=raeltime_xq_%i.csv",ui_xxtradexx_url] ;
			urls = [urls stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	  
			
            NSLog(@"URLS=%@",urls);            
			//利用網路下載物件來下載資料
			if (downloadobject.loadingData==NO) {
				downloadobject=nil;
				downloadobject=[[DownloadData alloc]init];
				downloadobject.delgete=self;
				[downloadobject StartDownload:urls  
								   identifier:[@"" stringByAppendingFormat:@"raeltime_xq_%i.csv",ui_xxtradexx_url]];	
				
				// upload_Tabel_Caption=[@"" stringByAppendingFormat:@"raeltime_xq_%i.csv.run...",ui_xxtradexx_url];
				// [myTable reloadData];	
				
				ui_xxtradexx_url=ui_xxtradexx_url+1;
				
			}
			
			
			
            
			
		}
        
		
	}
    
    
}
-(void)onUploadError:(id)non {
    
}

#pragma mark -
#pragma mark  ftp 回應事件
- (void)uploadFinished:(S7FTPRequest *)request {
	
	NSLog(@"Upload finished=%@" ,[request.filePath lastPathComponent] );
	
	upload_Tabel_Caption_FTP=[[request.filePath lastPathComponent] stringByAppendingString:@" 成功" ];
	[myTable reloadData];
	
	//[request release]; //增加此行會當機
	
	ui_chiefox=ui_chiefox+1;//因為開始使已經從0開始
	
	if ([uploadpathfile_chiefox count]>ui_chiefox) {
		//尚未全部傳遞結束 
		//第一階段上傳至奇狐專用的整批檔案
		[self upload_mutarray_file_path:[uploadpathfile_chiefox objectAtIndex:ui_chiefox] server_path:@"/xxtradexx/webroot/chiefoxdata/"];
	}
	else{
		//第二階段上傳至歷史資料庫資料
		if ([uploadpathfile_xxtradexx count]>ui_xxtradexx) {
			
			[self upload_mutarray_file_path:[uploadpathfile_xxtradexx objectAtIndex:ui_xxtradexx] server_path:@"/xxtradexx/webroot/database/temp_xq/"];
			ui_xxtradexx=ui_xxtradexx+1;
			
		}
		else {
			//階段三開始
			NSString *urls;
			urls=@"";
			urls=[urls stringByAppendingFormat: @"http://www.xxtradexx.com/database/import_data_xq.aspx?ifaftclose=1&filename=raeltime_xq_%i.csv",ui_xxtradexx_url] ;
			
            
            urls = [urls stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	  
			
			//利用網路下載物件來下載資料
			if (downloadobject.loadingData==NO) {
				downloadobject=nil;
				downloadobject=[[DownloadData alloc]init];
				downloadobject.delgete=self;
				[downloadobject StartDownload:urls  
								   identifier:[@"" stringByAppendingFormat:@"raeltime_xq_%i.csv",ui_xxtradexx_url]];	
				
				// upload_Tabel_Caption=[@"" stringByAppendingFormat:@"raeltime_xq_%i.csv.run...",ui_xxtradexx_url];
				 //[myTable reloadData];	
				
				ui_xxtradexx_url=ui_xxtradexx_url+1;
				
			}
			
			
			
							
			
		}
	
		
	}
	
	
}

- (void)uploadFailed:(S7FTPRequest *)request {
	
	NSLog(@"Upload failed: %@", [request.error localizedDescription]);
	//[request release];
	UIAlertView *ia;
	ia=[[UIAlertView alloc] initWithTitle:@"資料處理" message:@"上傳奇狐檔案 失敗- (void)uploadFailed" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
	[ia show];	
	
}

- (void)uploadWillStart:(S7FTPRequest *)request {
	
	//NSLog(@"Will transfer %d bytes.", request.fileSize);
}

- (void)uploadBytesWritten:(S7FTPRequest *)request {
	
	//NSLog(@"Transferred: %d", request.bytesWritten);
}


- (void)requestStatusChanged:(S7FTPRequest *)request {
	
	switch (request.status) {
		case S7FTPRequestStatusNone:
            NSLog(@"StatusNone.");
			break;
        case S7FTPRequestStatusOpenNetworkConnection:
			NSLog(@"Opened connection.");
			break;
		case S7FTPRequestStatusReadingFromStream:
			NSLog(@"Reading from stream...");
			break;
		case S7FTPRequestStatusWritingToStream:
			NSLog(@"Writing to stream...");
			break;
		case S7FTPRequestStatusClosedNetworkConnection:
			NSLog(@"Closed connection.");
			break;
		case S7FTPRequestStatusError:{
			UIAlertView *ia;
			ia=[[UIAlertView alloc] initWithTitle:@"資料處理" message:@"上傳奇狐檔案 失敗- (void)requestStatusChanged" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
			[ia show];				
			
			NSLog(@"Error occurred.");
			break;
		}
	}
}
 
#pragma mark -
#pragma mark  url 回應結束失敗事件

-(void)Download_Finish:(NSString *)datas Oidentifier:(NSString*)OutIdentifier{
 
	

	NSArray *csvLines ;	
   // csvLines = [datas  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
	csvLines = [datas  componentsSeparatedByString:@"<br>"];
		
	if ([csvLines count]>0) {
		NSString *line;
		line = (NSString *)[csvLines objectAtIndex:0];		
		
		if ([line isEqualToString:@"OK"]) {
			
            if ([record_upload_type isEqualToString:@"FTP"]) {
                
                upload_Tabel_Caption_FTP=[[@"FTP 匯入資料處理中" stringByAppendingFormat:@"%i",ui_xxtradexx_url] copy] ;                
                
            }
            else if([record_upload_type isEqualToString:@"HTTP"]){
                  upload_Tabel_Caption_HTTP=[[@"HTTP 匯入資料處理中" stringByAppendingFormat:@"%i",ui_xxtradexx_url] copy] ;                    
            }
                           
           			
			[myTable reloadData];
			
			if ([uploadpathfile_xxtradexx count]>ui_xxtradexx_url) {
				
				NSString *urls;
				urls=@"";
				urls=[urls stringByAppendingFormat: @"http://www.xxtradexx.com/database/import_data_xq.aspx?ifaftclose=1&filename=raeltime_xq_%i.csv",ui_xxtradexx_url] ;
				urls = [urls stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	  
				
				//利用網路下載物件來下載資料
				if (downloadobject.loadingData==NO) {
					 
					downloadobject=nil;
					downloadobject=[[DownloadData alloc]init];
					downloadobject.delgete=self;
				 
					[downloadobject StartDownload:urls  
									   identifier:[@"" stringByAppendingFormat:@"raeltime_xq_%i.csv",ui_xxtradexx_url]];	
					
					
					 
					
					ui_xxtradexx_url=ui_xxtradexx_url+1;				
					 
				}			
				
				
			}
			else {
                   
                if ([record_upload_type isEqualToString:@"FTP"]) {
                    
                    upload_Tabel_Caption_FTP=@"FTP 完成";                
                    
                }
                else if([record_upload_type isEqualToString:@"HTTP"]){
                    upload_Tabel_Caption_HTTP=@"HTTP 完成" ;                    
                }

               
				[myTable reloadData];
			}
			
			
			
		}
		
		
	}
	else {
		
        if ([record_upload_type isEqualToString:@"FTP"]) {
            
            upload_Tabel_Caption_FTP=@"FTP :處理匯入資料庫失敗";                
            
        }
        else if([record_upload_type isEqualToString:@"HTTP"]){
            upload_Tabel_Caption_HTTP=@"HTTP :處理匯入資料庫失敗" ;                    
        }
         
		[myTable reloadData];
	
	} 
	
			
}
-(void)Download_didFailWithError:(NSError *)error Oidentifier:(NSString*)OutIdentifier{

}



@end
